import { Component } from 'react'
import Taro from '@tarojs/taro'
import { View, Text, OpenData } from '@tarojs/components'
import './index.scss'
import global from '../../global';
import { Button, Map, Swiper, SwiperItem, Picker, Input, Image } from '@tarojs/components'
import Request from '../../api/index'
import Event from '../../event';

export default class Index extends Component {

  constructor(props) {
    super(props);
    this.state = {
      userInfo: {
        ownerAuthStatus: '0',
        messageReminds: 0
      },
      auths: []
    }
    this.handleLogin = this.handleLogin.bind(this);
    this.getUserProfile = this.getUserProfile.bind(this);
    this.checkRegisterInfo = this.checkRegisterInfo.bind(this);
    this.getLatestUserInfo = this.getLatestUserInfo.bind(this);
    this.commonNavigate = this.commonNavigate.bind(this);
    Event.on('backFromBindingPage', this.getLatestUserInfo);
    Event.on('checkOperationRemind', (operationRemind) => {
      let {REFLASH_LOGIN_INFO, MESSAGE_LEFT} = operationRemind;
      this.setState({
        messageReminds: MESSAGE_LEFT.length
      });
      if (REFLASH_LOGIN_INFO.length > 0) {
        this.getLatestUserInfo();
        this.updateRemindStatus(REFLASH_LOGIN_INFO[0]);
      }
    })
  }

  async updateRemindStatus(operationRemind) {
    try {
      let res = await Request.get(`/business/operation_remind/updateStatus/${operationRemind.businessId}/REFLASH_LOGIN_INFO/${global.userInfo.userId}`);
      if (res.data.code !== 200) {
        throw new Error();
      }
      console.log(res.data.data)
    } catch (e) {
      console.log("更新状态异常")
    }
  }

  componentWillMount () { }

  componentDidMount () {

  }

  componentWillUnmount () { }

  componentDidShow () {
    if (global.isLogin) {
      this.setState({
        userInfo: global.userInfo
      })
    }
    if (global.messageReminds && global.messageReminds > 0) {
      this.setState({
        messageReminds: global.messageReminds
      });
    }

  }

  componentDidHide () { }

  async getLatestUserInfo() {
    if (!global.userInfo.userId) {
      return;
    }
    let res = await Request.get(`/business/wx_user/getInfoWithAuth/${global.userInfo.userId}`);
    if (res.data.code !== 200) {
      console.log('获取最新用户数据失败');
    }
    global.userInfo = res.data.data;
    this.setState({
      userInfo: res.data.data,
      bindingVillages: res.data.data.bindings,
      bindingVillageName: res.data.data.bindings[0].villageName
    })
    if (res.data.data.bindings.length > 0) {
      this.setState({
        bindingVillageName: res.data.data.bindings[0].villageName
      })
      global.currentBindingVillage = res.data.data.bindings[0];
    }
  }

  /**
   * 获取登录code
   * @returns {Promise<string>}
   */
  async getLoginCode() {
    let loginRes = await Taro.login();
    if (!loginRes.code) {
      throw new Error('小程序Login接口异常');
    }
    return loginRes.code
  }

  /**
   * 登录注册逻辑
   * @param loginInfo
   * @returns {Promise<Error|boolean>}
   */
  async handleLogin(loginInfo) {
    try {
      loginInfo.code = await this.getLoginCode();
      let res = await Request.post('/wx/login', loginInfo);
      if (res.data.code !== 200) {
        throw new Error(res.data.msg);
      }
      global.isLogin = true;
      global.isRegister = true;
      // global.setToken(res.data.data);
      global.token = res.data.data.token;
      global.userInfo = res.data.data.wxUser;
      return true;
    } catch (e) {
      await Taro.hideLoading();
      console.log(e)
      await Taro.showModal({
        title: e.toString()
      });
      return false;
    }
  }
  randomString(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = $chars.length;
    var pwd = '';
    for (let i = 0; i < len; i++) {
      pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
  }

  /**
   * 弹窗获取用户信息
   * @returns {Promise<void>}
   */
  async getUserProfile() {
    if (global.isLogin) {
      return ;
    }
    try {
      let userProfileRes =
        {
          userInfo: {
            "nickName": this.randomString(6),
            "gender":0,
            "language":"",
            "city":"",
            "province":"",
            "country":"",
            "avatarUrl":"https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132",
            "is_demote":true,
            "avatar":"https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132"
          }
        }
      await Taro.showLoading({
        title: '登录中...'
      })
      let res = await this.handleLogin(userProfileRes.userInfo);
      if (res === true) {
        this.setState({
          userInfo: {
            ...userProfileRes.userInfo,
            ownerAuthStatus: '0'
          }
        });
        await Taro.hideLoading();
        await Taro.showModal({
          title: "登录成功！"
        })
      }
    } catch (e) {
      await Taro.hideLoading();
      await Taro.showModal({
        title: JSON.stringify(e)
      });
      console.log(e)
    }

  }

  /**
   * 检测注册登录状态
   * @returns {Promise<void>}
   */
  async checkRegisterInfo() {
    try {
      let registerInfo = await Request.get(`/wx/isRegister?code=${await this.getLoginCode()}`);
      if (registerInfo.data.code === 20401) {
        throw new Error('尚未注册1')
      }
      console.log(registerInfo, 'sss');
      this.setState({
        userInfo: registerInfo.data.data.wxUser,
      });
      console.log(registerInfo.data.data.wxUser, 'ssss')
      global.isLogin = true;
      // global.setToken(registerInfo.data.data.token);
      global.token =  registerInfo.data.data.token;
      global.userInfo = registerInfo.data.data.wxUser;
      console.log('登录成功');
    } catch (e) {
      console.log(e)
    }
  }

  /**
   * 处理获取手机号逻辑
   */
  async getPhoneNumber(val) {
    await Taro.showLoading({
      title: '绑定中...',
      mask: true
    })
    try {
      let { encryptedData, iv } = val.detail;
      let res = await Request.post('/wx/bindPhoneNumber', {encryptedData, iv, wxUserId: global.userInfo.userId});
      if (res.data.code !== 200) {
        throw new Error()
      }
      global.userInfo.phone = res.data.data.phoneNumber;
      this.state.userInfo.phone = res.data.data.phoneNumber;
      this.setState({
        userInfo: this.state.userInfo
      })
      await Taro.hideLoading();
      await Taro.showModal({
        title: '提示',
        content: '绑定成功！',
        confirmText: '确定',
      })
    } catch (e) {
      console.log('绑定失败')
    } finally {
      await Taro.hideLoading();
    }

  }

  /**
   * 处理关于点击逻辑
   */
  async handleAbout() {
    await Taro.navigateTo({
      url: '/pages/about/index'
    })

  }

  async commonNavigate(url) {
    if (!global.isLogin) {
      await Taro.showModal({
        title: '提示',
        content: '您尚未登录',
        confirmText: '登录',
        success: (res) =>  {
          if (res.confirm) {
            this.getUserProfile()
          }
        }
      });
      return;
    }
    if (!global.userInfo.bindingVillageId || global.userInfo.ownerAuthStatus === '0') {
      await Taro.showModal({
        title: '提示',
        content: '您尚未绑定小区',
        confirmText: '去绑定',
        success: (res) => {
          if (res.confirm) {
            Taro.navigateTo({
              url: '/pages/binding/index'
            })
          }
        }
      });
      return;
    }

    if (global.userInfo.ownerAuthStatus === '1') {
      await Taro.showModal({
        title: '提示',
        content: '您的业主认证正在审核中，请等候审核通过',
        confirmText: '确定',
      });
      return;
    }
    await Taro.navigateTo({
      url: url
    })
  }

  render () {
    let {userInfo} = this.state;



    let companyAuthStatusComponentMap = {
      '0': <Text/>,
      '1': <Text className='primary_tag'>企业认证中</Text>,
      '2': <Text className='primary_tag'>企业认证</Text>,
      '3': <Text className='danger_tag'>企业认证废弃</Text>
    }
    let ownerAuthStatusComponentMap = {
      '0': <Text>尚未绑定小区</Text>,
      '1': <Text className='primary_tag'>业主认证中</Text>,
      '2': <Text className='primary_tag'>业主认证</Text>,
      '3': <Text className='danger_tag'>业主认证废弃</Text>
    }

    return (
      <View className='mine_container'>
        <View className='user_info_container'>
          <View className='avatar_container'>
            {/*<OpenData type='userAvatarUrl'/>*/}
            <Image mode={"widthFix"} src={userInfo.avatar ? userInfo.avatar : require('./img/avatar.png')}/>
          </View>

          <View className='info_detail_container'>
            <Text onClick={this.getUserProfile}>{userInfo.nickName || '点击登录'}</Text>
            <View className='community_auth_container' onClick={() => {
              if (global.isLogin && userInfo.ownerAuthStatus === '0') {
                Taro.navigateTo({url: '/pages/binding/index'})
              }
            }}>
              {
                ownerAuthStatusComponentMap[userInfo.ownerAuthStatus]
              }
              <Text style={{marginRight: '10px'}}/>
              {
                companyAuthStatusComponentMap[userInfo.companyAuthStatus]
              }
            </View>
          </View>
          <View className='handle_action_container'>
            {/*<Text className='iconfont icon-shezhi color-444 size50'/>*/}
            <Text onClick={() => Taro.navigateTo({url: '/pages/message/index'})} className='iconfont icon-xiaoxizhongxin color-444 size50'/>
            {
              this.state.messageReminds > 0 && <View className={'red_circle'}/>
            }
          </View>
        </View>
        <View className='children_app_container'>
          <View className='title_container'>
            <Text>个人服务</Text>
          </View>
          <View className='apps_container'>
            <View className='app_item' onClick={async () => {
              if (!global.isLogin) {
                await Taro.showModal({
                  title: '提示',
                  content: '您尚未登录',
                  confirmText: '登录',
                  success: (res) =>  {
                    if (res.confirm) {
                      this.getUserProfile()
                    }
                  }
                });
                return;
              }
              Taro.navigateTo({
                url: '/pages/binding_list/index'
              })
            }}>
              <Image src={require('./img/yzrz.svg')}/>
              <Text>业主认证</Text>
            </View>
            <View className='app_item' onClick={async () => await this.commonNavigate('/pages/cars_list/index')}>
              <Image src={require('./img/car.svg')}/>
              <Text>车辆认证</Text>
            </View>
            <View className='app_item' onClick={async () => await this.commonNavigate('/pages/company_auth/index')}>
              <Image src={require('./img/wdxx.svg')}/>
              <Text>公司认证</Text>
            </View>
            {/*<View className='app_item' onClick={async () => {*/}
            {/*  global.isGuest = true;*/}
            {/*  await this.commonNavigate('/pages/face_list/index')*/}
            {/*}}>*/}
            {/*  <Image src={require('./img/bsbx.svg')}/>*/}
            {/*  <Text>我的访客</Text>*/}
            {/*</View>*/}
            <View className='app_item' onClick={async () => await this.commonNavigate('/pages/family_members/index')}>
              <Image src={require('./img/jiating.svg')}/>
              <Text>家庭成员</Text>
            </View>
          </View>
          <View className='apps_container'>
            <View className='app_item' onClick={async () => {
              global.isApplyJob = false;
              await this.commonNavigate('/pages/recruit_management/index')
            }}>
              <Image src={require('./img/zhaopin.svg')}/>
              <Text>招聘专栏</Text>
            </View>
            <View className='app_item' onClick={async () => {
              global.isApplyJob = true;
              await this.commonNavigate('/pages/apply_info/index')
            }}>
              <Image src={require('./img/zhaopin.svg')}/>
              <Text>我的投递</Text>
            </View>
            <View className='app_item' onClick={async () => await this.commonNavigate('/pages/mine_house_rental/index')}>
              <Image src={require('./img/bsbx.svg')}/>
              <Text>我要出租</Text>
            </View>
          </View>
        </View>
        <View className='children_app_container' style={{paddingBottom: 0}}>
          <View className='title_container'>
            <Text>通用设置</Text>
          </View>
          <View className='settings_container'>
            <Button className='setting_item' hoverClass='none' openType={!userInfo.phone && 'getPhoneNumber' } onGetPhoneNumber={this.getPhoneNumber.bind(this)}>
              <Text className='iconfont icon-mobile-phone size36'/>
              <Text className='setting_label'>绑定手机号</Text>
              <Text className='color-DCDCDC size28'>{userInfo.phone || ''}</Text>
              <Text className='iconfont icon-arrow-right color-DCDCDC size32'/>
            </Button>
            <Button className='setting_item' hoverClass='none' openType='share'>
              <Text className='iconfont icon-share size36'/>
              <Text className='setting_label'>软件分享</Text>
              <Text className='iconfont icon-arrow-right color-DCDCDC size32'/>
            </Button>
            <Button className='setting_item' hoverClass='none' onClick={(val) => Taro.navigateTo({
              url: '/pages/feedback/index'
            })}>
              <Text className='iconfont icon-xiaoxi size36'/>
              <Text className='setting_label'>意见反馈</Text>
              <Text className='iconfont icon-arrow-right color-DCDCDC size32'/>
            </Button>
            <Button style={{border: 'none'}} hoverClass='none' className='setting_item' onClick={this.handleAbout.bind(this)}>
              <Text className='iconfont icon-prompt size36'/>
              <Text className='setting_label'>关于永裕管家</Text>
              <Text className='color-DCDCDC size28'>当前版本 1.0.2</Text>
              <Text className='iconfont icon-arrow-right color-DCDCDC size32'></Text>
            </Button>
          </View>
        </View>
      </View>
    )
  }
}
